package com.example.demo6.controller;


import com.example.demo6.utils.ResultVOUtils;
import com.example.demo6.vo.MovieVO;
import com.example.demo6.domain.Movie;
import com.example.demo6.repository.MovieRepository;
import com.example.demo6.vo.ResultVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * Rest风格电影控制器
 */
@RestController
@RequestMapping("/api/movie")
public class MovieRestController {

    @Autowired
    private MovieRepository movieRepository;

    /**
     * 查询电影列表
     *
     * @return
     * @url /api/movie/lists
     */
    @RequestMapping(value = "/lists", method = RequestMethod.GET)
    public ResultVO<List<MovieVO>> lists() {
        List<Movie> list = movieRepository.findAll();

        List<MovieVO> voList = new ArrayList<>();
        for (Movie movie : list) {
            MovieVO vo = new MovieVO();
            vo.setId(movie.getId());
            vo.setName(movie.getName());
            vo.setPhoto(movie.getPhoto());
            voList.add(vo);

        }

       /* ResultVO<List<MovieVO>> resultVO = new ResultVO<>();
        resultVO.setCode(200);
        resultVO.setMsg("success");
        resultVO.setData(voList);

        return resultVO;*/
        return ResultVOUtils.success(voList);

    }

    /**
     * 执行保存操作，然后重定向到列表页面 index.html
     *
     * @return
     */
    @RequestMapping(value = "/add", method = RequestMethod.POST)
    public ResultVO<MovieVO> doAdd(@RequestParam String name, @RequestParam String photo, @RequestParam String createDate) {


        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");

        Date date = null;
        try {
            date = format.parse(createDate);
        } catch (Exception e) {

        }

        Movie movie = new Movie();
        movie.setName(name);
        movie.setPhoto(photo);
        movie.setCreateDate(date);
        Movie result = movieRepository.save(movie);
//        ResultVO<MovieVO> resultVO = new ResultVO<>();
////        if (result !=null){
////            resultVO.setCode(200);
////            resultVO.setMsg("success");
////            resultVO.setData(new MovieVO(result));
////        }else{
////            resultVO.setCode(500);
////            resultVO.setMsg("fail");
////        }
////
////        return resultVO;


        if (result != null) {
            return ResultVOUtils.success(new MovieVO(result));
        } else {
            return ResultVOUtils.fail();
        }
    }

}